//
//  Share.m
//  Runner
//
//  Created by 谭圣 on 2023/5/11.
//

#import "Share.h"
#import <MessageUI/MessageUI.h>
//#import <Toast/Toast.h>
#import "QMUIKit/QMUIKit.h"
#define kAppName [[NSBundle mainBundle] infoDictionary][@"CFBundleDisplayName"]
#define kDocumentPath ([NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject])

@interface Share()<MFMailComposeViewControllerDelegate>
@property (weak, nonatomic) UIViewController *fromVc;
@end

@implementation Share

- (void)share:(NSString *)cmdStr from:(nonnull UIViewController *)fromVc {
    _fromVc = fromVc;
    
    NSString *path = [kDocumentPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@", [self _fileName]]];
    NSError *error;
    [cmdStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        UIAlertController *al = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"Share error %@", error] preferredStyle:UIAlertControllerStyleAlert];
        [fromVc presentViewController:al animated:YES completion:nil];
        return;
    }
    
    //发邮件
    if ([NSFileManager.defaultManager fileExistsAtPath:path]) {
        [self sendMail:path];
    }
}

- (NSString *)_fileName {
    //写入文件
    NSString *appName = [kAppName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *ext = [appName substringWithRange:NSMakeRange(appName.length-3, 3)];
    NSString *fileName = [NSString stringWithFormat:@"%@.%@", appName, ext];
    return fileName;
}

- (void)sendMail:(NSString *)path
{
    // 1.初始化编写邮件的控制器
    MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
    if (!mailViewController) {
        // 在设备还没有添加邮件账户的时候mailViewController为空，下面的present view controller会导致程序崩溃，这里要作出判断
        [QMUITips showError:@"Share fail:This device no set mail account."];
        return;
    }
    mailViewController.mailComposeDelegate = self;
    
    // 2.设置邮件主题
    [mailViewController setSubject:@"Share dsp data"];
    
    // 3.设置邮件主体内容
    [mailViewController setMessageBody:@"dsp data" isHTML:NO];
    
    // 4.添加附件
    NSData *attachmentData = [NSData dataWithContentsOfFile:path];
    //关于mimeType：http://www.iana.org/assignments/media-types/
    //    application
    //    audio
    //    font
    //    example
    //    image
    //    message
    //    model
    //    multipart
    //    text
    //    video
    [mailViewController addAttachmentData:attachmentData mimeType:@"text/example" fileName:[self _fileName]];
    
    // 5.呼出发送视图
    [_fromVc presentViewController:mailViewController animated:YES completion:nil];
}

#pragma mark - 实现 MFMailComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    //关闭邮件发送窗口
    [controller dismissViewControllerAnimated:YES completion:nil];
    NSString *msg;
    switch (result) {
        case MFMailComposeResultCancelled:
            //用户取消编辑邮件
            msg = @"Cancel mail.";
            break;
        case MFMailComposeResultSaved:
            //用户成功保存邮件
            msg = @"Saved mail.";
            if (self.onDone) {
                self.onDone();
            }
            break;
        case MFMailComposeResultSent:
            //用户点击发送，将邮件放到队列中，还没发送
            msg = @"Send mail success.";
            if (self.onDone) {
                self.onDone();
            }
            break;
        case MFMailComposeResultFailed:
            //用户试图保存或者发送邮件失败
            msg = @"Send mail fail.";
            break;
        default:
            msg = @"";
            break;
    }
    if (msg.length) {
        [QMUITips showInfo:@"msg"];
        
    }
}

@end
